// Threads (线程) 示例
program ThreadExample;

{$mode objfpc}{$H+}

uses
  Classes, SysUtils;

type
  // 定义一个简单的线程类
  TSimpleThread = class(TThread)
  private
    FThreadID: Integer;
    FCounter: Integer;
  protected
    procedure Execute; override;
  public
    constructor Create(AThreadID: Integer);
  end;

constructor TSimpleThread.Create(AThreadID: Integer);
begin
  inherited Create(False); // 创建后立即启动
  FThreadID := AThreadID;
  FCounter := 0;
  FreeOnTerminate := True; // 线程结束后自动释放
end;

procedure TSimpleThread.Execute;
var
  I: Integer;
begin
  for I := 1 to 5 do
  begin
    if Terminated then
      Exit;
      
    Inc(FCounter);
    WriteLn('线程 ', FThreadID, ' 正在运行，计数: ', FCounter);
    Sleep(1000); // 暂停1秒
  end;
  WriteLn('线程 ', FThreadID, ' 执行完毕');
end;

var
  Thread1, Thread2: TSimpleThread;

begin
  WriteLn('=== Pascal 线程示例 ===');
  WriteLn;
  
  // 创建并启动线程
  WriteLn('创建并启动线程...');
  Thread1 := TSimpleThread.Create(1);
  Thread2 := TSimpleThread.Create(2);
  
  // 等待线程完成
  WriteLn('等待线程完成...');
  Thread1.WaitFor;
  Thread2.WaitFor;
  
  WriteLn('所有线程执行完毕');
  WriteLn;
  WriteLn('线程示例完成。');
  ReadLn;
end.